#!/usr/bin/env python3
"""
Script to fix LaTeX ampersand (&) issues in chapter files.
Replaces problematic & characters with 'and' in chapter titles and section headings.
"""

import os
import re
from pathlib import Path

def fix_ampersand_in_file(file_path):
    """Fix ampersand issues in a single LaTeX file."""
    changes_made = 0
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # Fix patterns that commonly cause "Misplaced alignment tab character &" errors
        patterns_to_fix = [
            # Chapter titles
            (r'\\chapter\{([^}]*?)\s*&\s*([^}]*?)\}', r'\\chapter{\1 and \2}'),
            # Section titles
            (r'\\section\{([^}]*?)\s*&\s*([^}]*?)\}', r'\\section{\1 and \2}'),
            # Subsection titles
            (r'\\subsection\{([^}]*?)\s*&\s*([^}]*?)\}', r'\\subsection{\1 and \2}'),
            # Subsubsection titles
            (r'\\subsubsection\{([^}]*?)\s*&\s*([^}]*?)\}', r'\\subsubsection{\1 and \2}'),
        ]
        
        for pattern, replacement in patterns_to_fix:
            new_content = re.sub(pattern, replacement, content)
            if new_content != content:
                changes_made += content.count('&') - new_content.count('&')
                content = new_content
        
        # Write back if changes were made
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"Fixed {changes_made} ampersand issues in {file_path}")
            return changes_made
        else:
            print(f"No ampersand issues found in {file_path}")
            return 0
            
    except Exception as e:
        print(f"Error processing {file_path}: {e}")
        return 0

def main():
    """Main function to process all LaTeX files."""
    chapters_dir = Path('./chapters')
    
    if not chapters_dir.exists():
        print("Error: chapters directory not found!")
        return
    
    total_changes = 0
    processed_files = 0
    
    # Process all .tex files in chapters directory
    for tex_file in chapters_dir.glob('*.tex'):
        print(f"\nProcessing {tex_file}...")
        changes = fix_ampersand_in_file(tex_file)
        total_changes += changes
        processed_files += 1
    
    print(f"\n=== Summary ===")
    print(f"Processed files: {processed_files}")
    print(f"Total ampersand issues fixed: {total_changes}")
    
    if total_changes > 0:
        print("\nRecommendation: Re-run xelatex to verify fixes")

if __name__ == "__main__":
    main()